import Vue from "vue";
import Vuex from "vuex";
import user from "./modules/user";

Vue.use(Vuex);

export default new Vuex.Store({
	state: {
		token: localStorage.getItem("token") || "",
		userInfo: JSON.parse(localStorage.getItem("userInfo")) || {},
	},
	mutations: {
		SET_TOKEN(state, token) {
			state.token = token;
			localStorage.setItem("token", token);
		},
		SET_USER_INFO(state, userInfo) {
			state.userInfo = userInfo;
			localStorage.setItem("userInfo", JSON.stringify(userInfo));
		},
		LOGOUT(state) {
			state.token = "";
			state.userInfo = {};
			localStorage.removeItem("token");
			localStorage.removeItem("userInfo");
		},
	},
	actions: {
		// 用户登录
		login({ commit }, userInfo) {
			return new Promise((resolve, reject) => {
				setTimeout(() => {
					const { username, password } = userInfo;
					if (username === "admin" && password === "123456") {
						const token = "mock-token-" + Math.random().toString(36).substr(2);
						const userInfo = {
							id: 1,
							username: "admin",
							name: "管理员",
							avatar:
								"https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png",
						};
						commit("SET_TOKEN", token);
						commit("SET_USER_INFO", userInfo);
						resolve();
					} else {
						reject(new Error("用户名或密码错误"));
					}
				}, 500);
			});
		},
		// 退出登录
		logout({ commit }) {
			return new Promise((resolve) => {
				commit("LOGOUT");
				resolve();
			});
		},
	},
	modules: {
		user,
	},
	getters: {
		token: (state) => state.user.token,
		userInfo: (state) => state.user.userInfo,
	},
});
